//
//  WebViewController.swift
//  ToBeBigFE
//
//  Created by mingo on 2020/2/8.
//  Copyright © 2020 com.example. All rights reserved.
//

import UIKit
import WebKit

class WebViewController: UIViewController, WKUIDelegate {

    var webView: WKWebView!

    override func viewDidLoad() {
        super.viewDidLoad()
        
        let config = WKWebViewConfiguration()
        let birdge = BridgeHandler()
        config.userContentController.add(birdge, name: "iOSBridge")
        
        webView = WKWebView(frame: self.view.frame, configuration: config)
        webView.uiDelegate = self
        self.view.addSubview(webView)
        
        birdge.webView = webView
        birdge.viewController = self
        birdge.initModules()
        
        let url = URL(string: getLoadUrl())!
        let request = URLRequest(url: url)
        webView.load(request)
    }
    
    func getLoadUrl() -> String {
        return ""
    }
}

protocol BridgeModule : class {
    func callFunc(_ funcName: String, arg: [String: Any?])
}

class BridgeHandler : NSObject, WKScriptMessageHandler {
    
    var webView: WKWebView!
    var viewController: WebViewController!
    var moduleDict = [String:BridgeModule]()
    
    func initModules() {
        moduleDict["UI"] = JSBridgeUI(viewController: viewController)
    }
    
    func userContentController(
        _ userContentController: WKUserContentController,
        didReceive message: WKScriptMessage)
    {
        let body = message.body as! [String: Any]
        print("WebView callNative ok. body is \(body)")
        
        let callbackId = body["callbackId"] as! String
        let method = body["method"] as! String
        let data = body["data"] as! String
        guard let arg = try? JSONSerialization.jsonObject(with: data.data(using: .utf8)!, options: []) else {
            return
        }
        
        let split = method.split(separator: ".")
        let moduleName = String(split[0])
        let funcName = String(split[1])
        
        moduleDict[moduleName]?.callFunc(funcName, arg: arg as! [String:Any])
    }
}

class JSBridgeUI : BridgeModule {
    
    let viewController: WebViewController
    
    init(viewController: WebViewController) {
        self.viewController = viewController
    }
    
    func callFunc(_ funcName: String, arg: [String : Any?]) {
        switch funcName {
        case "toast":
            toast(arg)
        default: break
        }
    }
    
    func toast(_ arg: [String : Any?]) {
        let message = arg["message"] as! String
        viewController.view.makeToast(message)
    }
}
